package com.jiutong.meipengdai.ui.activitys;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.jiutong.meipengdai.R;
import com.jiutong.meipengdai.base.BaseActivity;
import com.jiutong.meipengdai.entity.BaseRespond;
import com.jiutong.meipengdai.entity.CheckPhoneNumRespond;
import com.jiutong.meipengdai.entity.IdentifyCodeRespond;
import com.jiutong.meipengdai.http.model.interfaces.RegisterAndLoginBiz;
import com.jiutong.meipengdai.http.model.requests.CheckPhoneNumRequest;
import com.jiutong.meipengdai.http.present.UserInfoPresent;
import com.jiutong.meipengdai.http.subscribers.ProgressSubscriber;
import com.jiutong.meipengdai.http.subscribers.SubscriberOnNextListener;
import com.jiutong.meipengdai.utils.StringUtil;
import com.jiutong.meipengdai.utils.TimerUtil;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 作用:
 * Created by 78 on 2017/6/17.
 */
public class EditPhoneActivity extends BaseActivity implements RegisterAndLoginBiz {

    @Bind(R.id.tv_title)
    TextView tv_title;
    @Bind(R.id.et_new_phone)
    EditText et_new_phone;
    @Bind(R.id.et_identify_code)
    EditText et_identify_code;
    @Bind(R.id.tv_getcode)
    TextView tv_getcode;
    @Bind(R.id.btn_edit_submit)
    Button btn_edit_submit;

    private UserInfoPresent userInfoPresent;
    private RegisterAndLoginBiz mRegisterBiz;
    private String identifyCode;
    private SubscriberOnNextListener onNextListener;
    private HashMap<String, Object> fieldsMap;
    private ProgressSubscriber progressSubscriber;
    private CheckPhoneNumRequest checkPhoneNumRequest;


    private TimerUtil timerUtil;


    @Override
    public int getLayoutResouceId() {
        return R.layout.activity_edit_phone;
    }


    @Override
    protected void initView() {
        super.initView();
        ButterKnife.bind(this);

        tv_title.setText(R.string.change_phone);
        //设置未正确填写状态
        btn_edit_submit.setEnabled(false);
        EditTextChange etc = new EditTextChange();
        et_new_phone.addTextChangedListener(etc);
        et_identify_code.addTextChangedListener(etc);

        //倒计时工具类
        timerUtil = new TimerUtil(tv_getcode);
        timerUtil.setCountTimer();

        userInfoPresent = new UserInfoPresent(this, this);

    }

    class EditTextChange implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            boolean isPwdOk = getNewPhone().length() == 11;
            boolean isRePwdOk = getVerificatCode().length() == 6;
            if (isPwdOk && isRePwdOk) {
                btn_edit_submit.setBackgroundResource(R.drawable.selector_orange_btn_bg);
                btn_edit_submit.setEnabled(true);
            } else {
                btn_edit_submit.setBackgroundResource(R.drawable.shape_light_gray_btn);
                btn_edit_submit.setEnabled(false);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    }

    @OnClick({R.id.rl_back, R.id.tv_getcode, R.id.btn_edit_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_back:
                finish();
                break;
            case R.id.tv_getcode:  //新手机验证码
                if (!isRightPhone())
                    return;
                isPhoneOk();
                break;
            case R.id.btn_edit_submit:  //确认修改
                if (!isRightAction())
                    return;
                userInfoPresent.changePhoneNum();
                break;
        }

    }

    private void isPhoneOk() {
        if (checkPhoneNumRequest == null) {
            checkPhoneNumRequest = new CheckPhoneNumRequest();
        }
        onNextListener = new SubscriberOnNextListener<CheckPhoneNumRespond>() {
            @Override
            public void onNext(CheckPhoneNumRespond object) {
                CheckPhoneNumRespond respond = (CheckPhoneNumRespond) object;
                if (respond.getResCode().equals("200")) {
                    userInfoPresent.getAuthCode();
                } else {
                    toastShortShow(respond.getResDesc());
                }

            }

            @Override
            public void onError(Throwable e) {

            }
        };
        fieldsMap = new HashMap<>();
        fieldsMap.put("phoneNo", getPhoneNum());
        progressSubscriber = new ProgressSubscriber(onNextListener, mContext);
        checkPhoneNumRequest.checkPhoneNum(progressSubscriber, fieldsMap);
    }

    /**
     * 输入手机号是否正确
     *
     * @return
     */
    private boolean isRightPhone() {
        if (TextUtils.isEmpty(getNewPhone())) {
            toastShortShow("请输入新手机号码");
            return false;
        }

        if (!StringUtil.isMobileNumber(getNewPhone())) {
            toastShortShow("手机号码格式有误，请输入正确手机号码");
            return false;
        }
        return true;
    }

    /**
     * 操作是否正确
     *
     * @return
     */
    private boolean isRightAction() {
        if (!isRightPhone()){
            return false;
        }

        if (TextUtils.isEmpty(getVerificatCode())) {
            toastShortShow("请输入手机验证码");
            return false;
        }
        if (!identifyCode.equals(getVerificatCode())) {
            toastShortShow("您输入的验证码不正确,请重新输入");
            return false;
        }
        return true;
    }


    @Override
    public String getPhoneNum() {
        return et_new_phone.getText().toString().trim();
    }

    @Override
    public String getPassword() {
        return null;
    }

    @Override
    public String getVerificatCode() {
        return et_identify_code.getText().toString().trim();
    }

    @Override
    public String getOriPwd() {
        return null;
    }

    @Override
    public String getNewPwd() {
        return null;
    }

    @Override
    public String getRelName() {
        return null;
    }

    @Override
    public String getIdCard() {
        return null;
    }

    @Override
    public String getEmail() {
        return null;
    }

    @Override
    public String getNewPhone() {
        return et_new_phone.getText().toString().trim();
    }

    @Override
    public String getCardNumber() {
        return null;
    }

    @Override
    public void onVerCodeGetSuccess(IdentifyCodeRespond subjects) {
        if (subjects.getResCode().equals("200")) {
            timerUtil.startTimer();
            identifyCode = subjects.getData();
        } else {
            toastShortShow(subjects.getResDesc());
        }
    }

    @Override
    public void onSuccess(Object object) {
        BaseRespond respond = (BaseRespond) object;
        if (respond.getResCode().equals("200")) {
            toastShortShow(respond.getResDesc());
            Bundle bundle = new Bundle();
            bundle.putString("phoneNum", getPhoneNum());
            openActivity(AccountSettingActivity.class, bundle);
            finish();
        } else {
            toastShortShow(respond.getResDesc());
        }
    }

    @Override
    public void onError(Throwable e) {

    }
}
